<script setup>
import { FilterMatchMode } from 'primevue/api';
import { ref, onBeforeMount,onMounted, computed } from 'vue';
// pinia的使用
import { useAppStore } from '../stores/app';
import { toRefs } from 'vue';
const { langIndex } = toRefs(useAppStore());

// 导入根目录下的easyhpc.json
import easyhpc from '../../easyhpc.json';

// 从路由中获取name
import { useRoute } from 'vue-router';
const route = useRoute();

// 组件
import { useToast } from 'primevue/usetoast';
import { useConfirm } from 'primevue/useconfirm';
const confirm = useConfirm();
const toast = useToast();

const dialogHeader = ref('');
const selected = ref([]); //选中的复选框
const chip = ref({}); //文本框展示当前信息


// 导入后端数据方法
import ProductService from '@/service/ProductService';
const productService = new ProductService();
const columns = ref([]);
const tableData = ref([]);
onMounted(() => {
    console.log(route.name);
    if (route.name === 'NoDe') {
    productService.getNodeList().then((data) => {
        columns.value = data[0];
        tableData.value = data.slice(1).map(row => columns.value.reduce((acc, col, i) => {
            acc[col] = row[i];
            return acc;
        }, {}));
    });}
    else if (route.name === 'FiLe') {   
    productService.getFileList().then((data) => {
        columns.value = data[0];
        tableData.value = data.slice(1).map(row => columns.value.reduce((acc, col, i) => {
            acc[col] = row[i];
            return acc;
        }, {}));
    });}
});



onBeforeMount(() => {
    initializeData();
});
// 动态数据以表格形式展现出来
const selectedActions = ref([]);
const columns1 = ref([]);
const tableData1 = ref([]);
const initializeData = () => {
    // my 2D array data
    const data = [
        ['Name', 'Age', 'City'],
        ['John1', 30, 'New York'],
        ['Alice1', 28, 'Los Angeles'],
        ['Bob1', 25, 'Chicago'],
        ['John2', 30, 'New York'],
        ['Alice2', 28, 'Los Angeles'],
        ['Bob2', 25, 'Chicago'],
        ['John3', 30, 'New York'],
        ['Alice3', 28, 'Los Angeles'],
        ['Bob3', 25, 'Chicago']
    ];
    columns1.value = data[0];
    tableData1.value = data.slice(1).map((row) => Object.fromEntries(columns1.value.map((col, i) => [col, row[i]])));
    selectedActions.value = tableData1.value.map(() => {
        return { name: '请选择' };
    });
};

const setDialog = ref(false);
const addDialog = ref(false);
// 编辑事件
const handleSet = (data) => {
    setDialog.value = true;
    dialogHeader.value = '编辑(set)';
    console.log(data);
    chip.value = data;
};
// 底栏--添加
const addData = ref([]);
const handleAdd = () => {
    dialogHeader.value = '添加(add)';
    addDialog.value = true;
    addData.value = chip.value;
};
// 底栏--删除
const confirmDeleteSelected = () => {
    confirm.require({
        message: '您是否想要删除选中记录?',
        header: '删除确认',
        icon: 'pi pi-info-circle',
        acceptClass: 'p-button-danger',
        accept: () => {
            const names = selected.value.map((item) => item);
            const newList = tableData.value.filter((item) => !names.includes(item));
            tableData.value = newList;
            toast.add({ severity: 'info', summary: 'Confirmed', detail: 'Record deleted', life: 3000 });
            // 删除之后，选中数据置空todotodotodo
            selected.value = [];
        },
        reject: () => {
            toast.add({ severity: 'error', summary: 'Rejected', detail: 'You have rejected', life: 3000 });
        }
    });
};
// 弹框取消功能
const hideDialog = () => {
    addDialog.value = false;
    setDialog.value = false;
};

// 弹框确认功能
const saveDialog = () => {
    // 新增时确认（深拷贝）
    if (dialogHeader.value == '添加(add)') {
        const data = JSON.parse(JSON.stringify(addData.value));
        // 新增时，数据添加到tableData
        tableData.value.push(data);
        addDialog.value = false;
        setDialog.value = false;
    } else {
        // 编辑时确认
        addDialog.value = false;
        setDialog.value = false;
    }
};

// 搜索功能
const filters = ref({});
const initFilters = () => {
    filters.value = {
        global: { value: null, matchMode: FilterMatchMode.CONTAINS }
    };
};
onBeforeMount(() => {
    initFilters();
});

// let type = '';
let type = ref('');

// 过滤json数据获取name属性值
console.log(route.name);
const filterJsonArr = computed(() =>
    easyhpc.filter((obj) => {
        return obj.name === route.name;
    })
);
console.log(filterJsonArr.value);

// bootstrap
// const arr = filterJsonArr.value[0].command.map((item) => item);
// console.log(arr);
// const firstKeys = arr.map((obj) => Object.keys(obj)[0]);
// console.log(firstKeys);
// const actions = firstKeys.map((item) => ({ name: item }));

// node
const actions = computed(() => {
    return filterJsonArr.value[0].command.map((item) => ({ name: item.lang[langIndex.value] }));
}); //0：中文，1：英文2:日语
console.log(actions);

// 所有command处理事件
const handleAction = (data, index) => {
    // console.log(data);
    console.log(selectedActions.value[index].name);

    if (selectedActions.value[index].name === '修改'|| selectedActions.value[index].name === 'set') {
        console.log('编辑');
        setDialog.value = true;
        dialogHeader.value = type.value;
        chip.value = data;
    } else if (selectedActions.value[index].name === '删除'||selectedActions .value[index].name === 'delete') {
        console.log('删除');
        confirm.require({
            message: '您是否想要删除当前条记录?',
            header: '删除确认',
            icon: 'pi pi-info-circle',
            acceptClass: 'p-button-danger',
            accept: () => {
                tableData.value.splice(index, 1);
                toast.add({ severity: 'info', summary: 'Confirmed', detail: 'Record deleted', life: 3000 });
            },
            reject: () => {
                toast.add({ severity: 'error', summary: 'Rejected', detail: 'You have rejected', life: 3000 });
            }
        });
    } else if (selectedActions.value[index].name === 'import') {
        console.log('import');
    } else if (selectedActions.value[index].name === 'export') {
        console.log('export');
    } else if (selectedActions.value[index].name === 'list') {
        console.log('export');
    } else if (selectedActions.value[index].name === 'new') {
        console.log('new');
    } else if (selectedActions.value[index].name === 'print') {
        console.log('print');
    } else if (selectedActions.value[index].name === 'clone') {
        console.log('clone');
    } else if (selectedActions.value[index].name === 'edit') {
        console.log('edit');
    } else if (selectedActions.value[index].name === 'update') {
        console.log('update');
    }
};
</script>

<template>
    <!-- 引入官方组件 -->
    <Toast />
    <ConfirmDialog />   
    <!-- 表格 -->
    <DataTable :value="tableData" scrollable scrollHeight="400px" v-model:selection="selected" :filters="filters" removableSort>
        <!-- 搜索功能 -->
        <template #header>
            <div class="flex flex-column md:flex-row md:justify-content-between md:align-items-center">
                <h5 class="m-0">Manage Products</h5>
                <span class="block mt-2 md:mt-0 p-input-icon-left">
                    <i class="pi pi-search" />
                    <InputText v-model="filters['global'].value" placeholder="Search..." />
                </span>
            </div>
        </template>
        <!-- 复选框功能 -->
        <Column selectionMode="multiple" headerStyle="width: 3rem"></Column>
        <!-- 表格数据 -->
        <Column v-for="(col, index) in columns" :key="index" :field="col" :header="col" sortable />
        <Column header="操作">
            <template #body="{ data, index }">
                <div style="display: flex">
                    <!-- dropdown -->
                    <div class="flex gap-1 justify-content-center">
                        <Button icon="pi pi-user-edit" severity="info" text aria-label="Filter" v-tooltip.bottom="{ value: '编辑', autoHide: true }" @click="handleSet(data)" />
                        <Dropdown v-model="selectedActions[index]" :options="actions" optionLabel="name" class="h-3rem" @change="handleAction(data, index)"> </Dropdown>
                    </div>
                </div>
            </template>
        </Column>
    </DataTable>
    <!-- 底栏功能 -->
    <div class="card flex flex-wrap gap-3 justify-content-center">
        <Button @click="handleAdd()" icon="pi pi-plus" label="ADD" />
        <Button @click="confirmDeleteSelected()" label="Delete" icon="pi pi-trash" :disabled="!selected.length" />
        <Button label="Revert" icon="pi pi-undo" disabled />
    </div>
    <!-- “编辑”弹框 -->
    <Dialog v-model:visible="setDialog" :modal="true" class="p-fluid" :header="dialogHeader" :style="{ width: '50vw' }">
        <div class="card p-fluid">
            <div class="field" v-for="(col, index) in columns" :key="col" :field="col" :header="col">
                <label>{{ columns[index] }}</label>
                <InputText type="text" v-model="chip[col]"></InputText>
            </div>
        </div>
        <template #footer>
            <Button label="Cancel" icon="pi pi-times" class="p-button-text" @click="hideDialog" />
            <Button label="Save" icon="pi pi-check" class="p-button-text" @click="saveDialog(index)" />
        </template>
    </Dialog>
    <!-- “添加”弹框 -->
    <Dialog v-model:visible="addDialog" :style="{ width: '450px' }" :header="dialogHeader" :modal="true" class="p-fluid">
        <div class="card p-fluid">
            <div class="field" v-for="(col, index) in columns" :key="col" :field="col" :header="col">
                <label>{{ columns[index] }}</label>
                <InputText id="name1" type="text" v-model="addData[col]"></InputText>
            </div>
        </div>
        <template #footer>
            <Button label="Cancel" icon="pi pi-times" class="p-button-text" @click="hideDialog" />
            <Button label="Save" icon="pi pi-check" class="p-button-text" @click="saveDialog" />
        </template>
    </Dialog>
</template>

<style scoped lang="scss">
::v-deep .p-dropdown-label.p-inputtext.p-placeholder {
    display: none;
}
::v-deep .p-dropdown-label.p-inputtext {
    display: none;
}
::v-deep .p-dropdown {
    border: 0;
}
</style>
